function DeBug(){
    ShowMsg("")
    let url = $("#url").val()
    let model = $("#debugModel option:selected").val()
    if(!reg.test(url) && $.inArray(url,rightModels) != -1){
        ShowMsg("请检查页面网址是否正确,http或者https一定得带哦！");
        return
    }
    if($.inArray(model,yaliModels) != -1){
        apiSend("PressureTest")
    }else if($("#debugModel option:selected").val() == "CHEST"){
        let chest = $("input[name='chest']:checked").val()
        if (chest == "IPTOCITY"){
            ipToCity()
        }else if(chest == "STRSEARCH"){
            strSeach(0)
        }else if(chest == "DIRSEARCH"){
            strSeach(1)
        }else if(chest == "TIMETODATE"){
            timeToDate()
        }
    }else if($("#debugModel option:selected").val() == "REGXP"){
        regXp()
    }else{
        clearInterval(setIntervalId);
        x = parseInt($("#Second").val());
        XId = 0;
        DaoJiShi();
    }
}


//修改placeholder
function changePlaceholder(){
    let model = $("#debugModel option:selected").val()
    let msg = ""
    if ($.inArray(model, urlModels) != -1) {
        msg = "大神，网址记得带上http或者https哦"
    }else if(model == "REGXP"){
        msg = "大神，填写正则的时候前后不要带//哦！"
    }else if(model == "CHEST"){
        msg = "请根据下面的单选按钮输入正确的内容！"
    }
    if(modelsUrlValues[model]){
        $("#url").val(modelsUrlValues[model])
    }else{
        $("#url").val("")
    }
    $("#url").attr("placeholder",msg);
}

function url(){
    if($("#debugModel option:selected").val() == "REGXP"){
        regXp();
    }
}

function GetDir(InitNum){
    $(".serachP").show("slow")
    $("#url").attr("placeholder","大神，这里你可以输入你想要搜索的字符串！");
    
    let dirReg = /\/?/
    if((dirReg.test($(".nowPath").html()) && CurrentDir.length < 1 && InitNum == 0) || (InitNum == 1 && dirReg.test($(".nowPath").html()))){
        //获取系统目录
        let Data = {};
        Data.type = "GetPathInfo";
        Data.data = "disk";
        ws.send(json(Data))   
    }
}
//改变百宝箱的模式 serachP
function changeChest(InitNum){
    if($.inArray($("input[name=chest]:checked").val(),fileSystemModels2) != -1  || $.inArray($("#debugModel option:selected").val(),fileSystemModels) != -1){
        GetDir(InitNum)
    }else{
        $(".serachP").hide("slow")
    }
}
//切换模式
function changeModel(){
    //清除文档信息，防止页面卡顿
    $("#regStr").val("")
    $(".apiBody pre").html("")

    changePlaceholder() //修改输入框的提示信息
    let model = $("#debugModel option:selected").val()
    if($.inArray(model, rightModels) != -1){
        $("#code").val("")
        $(".fileDir").html("")
        $(".codeBox").hide("slow")
        $(".lockPageDisplaySpan").hide("slow")
        closeiframeHeightSet() //先关闭修改高度
        stop();
        $(".apiBody").show("slow")
        $("#iframe").hide("slow");
        if($.inArray($("#debugModel option:selected").val(),yaliModels) == -1){
            $(".params").hide("slow")
            if($("#debugModel option:selected").val() == "REGXP"){
                pageGet();//防止火狐等浏览器缓存 记录不显示
                $(".regText").show("slow")
                $(".chestBox").hide("slow")
            }else{
                changeChest(0);
                $(".regText").hide("slow")
                $(".chestBox").show("slow")
            }
        }else{
            $(".bingfa-params,.params").show("slow")
            $(".regText,.chestBox").hide("slow")
        }
        $(".YALISHOW").hide("slow");
        $("#OpenMysql").attr("data-status","no")
        OpenMysql()
        $(".box").animate({
            left:"50%",
            width:"50%",
            height:"100%",
            bottom:"-30px",
        },800)
        $("#OpenMysql").hide("slow");
    }else{
        $("#DeBug").css("pointer-events","auto")
        $(".bingfa-params").hide("slow")
        $(".regText").hide("slow")
        $(".lockPageDisplaySpan").show("slow")
        if($("#debugModel option:selected").val() == "NORMAL"){
            $(".iframeHeightSetP").show("slow");
            $("#iframe").show("slow"); 
           $(".apiBody").hide("slow")
        }else{
            $(".iframeHeightSetP").hide("slow");
            $("#iframe").hide("slow");
            $(".apiBody").show("slow")
        }

        $(".YALISHOW").show("slow");
        $("#OpenMysql").show("slow");
        $(".params").show("slow");
        $(".box").animate({
            left:"0px",
            width:"100%",
            bottom:"0px",
            height: (216 + 55 * ($("#params-form p").length - 1)) + "px",
        },800)
        $("#OpenMysql").attr("data-status","yes")
        if(ChangeChanelCount == 0){
             OpenMysql()
        }
        iframeWidthSet();
        lockPageDisplay();
    }   
    if($("#isOpen").val() == "yes"){
        DeBug()
    }
    ShowMsg(""); //清空提示
    ChangeChanelCount++
}


function lockPageDisplay(){
    if(id("lockPageDisplay").checked){
        $(".setHetBox").show("slow");
        iframeWidthSet();
        setIframeHeight();
        GetDir(0)
    }else{
        closeiframeHeightSet()
    }
}
//停止刷新
function stop(){
    $("#isOpen").val("no")
    clearInterval(setIntervalId);
    $("#ShowMsg").html("");
}

function DaoJiShi(){
    $("#isOpen").val("yes")
    var url = $("#url").val();
    var iframe = id("iframe");
    var Second = parseInt($("#Second").val());
    if(!reg.test(url)){
        ShowMsg("请检查页面网址是否正确,http或者https一定得带哦！");
        return
    }	
    if(x<=0){
        x=Second;
        $("#ShowMsg").html("刷新中......请稍等");
        clearInterval(setIntervalId);
        reGet(iframe);
    }else{
        if(x == Second && XId == 0){//第一次点击进来
            reGet();
            XId++;
        }
        $("#ShowMsg").html("还有<i>" + x + "</i>秒将刷新！");
        x--;
    }
}

//刷新
function reGet(){
    let m = $("#debugModel option:selected").val();
    let url = $("#url").val();
    let iframe = id("iframe");
   
    if(m != "NORMAL"){
        $(".apiBody").css("display","block");
        apiSend("api");
    }else{
        $(".apiBody").css("display","none");
        let urlReg = /\?/g
        if(urlReg.test(url)){
            url += "&t="
        }else{
            url += "?t="
        }
        url += "t=" + Math.random()
        iframe.setAttribute("src",url); 
    }
    setIntervalId = setInterval("DaoJiShi()",1000); 
}
//api请求
function apiSend(type){

    Data = {};
    Data.type = type;
    Data.model = $("#debugModel option:selected").val();
    Data.url = $("#url").val();


   let params = ""
   let headerParams = ""
   let cookieParams = ""
   let paramsIndex = 0
   let headerParamsIndex = 0
   let cookieParamsIndex = 0
    $("#params-form p").each(function(i){

        k = $("#params-form p").eq(i).find(".key").val();
        v = $("#params-form p").eq(i).find(".value").val();
        let normalReg = /normal/g
        let headerReg = /header/g
        //获取选中的类别
        let checkName = $(this).find("input").eq(0).attr("name") 
        let keyValueType = $(this).find("input[name='" + checkName + "']:checked").val()
        if(k != ""){
            let  keyValueStr = k + "=" + v
            if(normalReg.test(keyValueType)){
                if(paramsIndex > 0) {
                    params += "&" + keyValueStr
                }else{
                    params += keyValueStr
                    paramsIndex++
                }
            }else if(headerReg.test(keyValueType)){
                if(headerParamsIndex > 0) {
                    headerParams += "&" + keyValueStr
                }else{
                    headerParams += keyValueStr
                    headerParamsIndex++
                }
            }else{
                if(cookieParamsIndex > 0) {
                    cookieParams += "&" + keyValueStr
                }else{
                    cookieParams += keyValueStr
                    cookieParamsIndex++
                }
            }
        }     
    })
    
    if(type == "PressureTest"){
        if ($(".C").val().length  < 1 || $(".N").val().length < 1){
            ShowMsg("并发数或者链接数为空");
            return
        }else if(parseInt($(".C").val()) > parseInt($(".N").val())){
            ShowMsg("并发数不能大于链接数");
            return
        }else{
            Data.C = $(".C").val()
            Data.N = $(".N").val()
            ShowMsg("")
            Data.agreement = "no"
            if($("input[name='agreement']:checked").val()){
                Data.agreement = $("input[name='agreement']:checked").val();
            }
            $("#DeBug").css("pointer-events","none"); //防止重复点击
            $(".apiBody pre").html("<div class='jindu'></div><div class='JieGuo' >进度：<progress value='0' max='100.00'></progress> <span class='progress-span'>0</span>%</div>");
        }

    }

    Data.data = params
    Data.headerParams = headerParams
    Data.cookieParams = cookieParams
    Data = json(Data)
    //发送数据到服务器
    ws.send(Data)
}
function OpenMysql(){
    if($("#OpenMysql").attr("data-status") == "yes"){
        if(ChangeChanelCount !=0){
            closeMysql("yes")
        }
        if($.inArray($("#debugModel option:selected").val(),rightModels) != -1){
           // ShowMsg("抱歉，侧栏模式暂时不打开监控哦！")
            return 
        }
        $("#Mysqlbox").show("slow")
        $("#OpenMysql").html("隐藏mysql监控");
        $("#OpenMysql").attr("data-status","no");
    }else{
        if(ChangeChanelCount !=0){
            closeMysql("no")
        }
        $("#OpenMysql").html("打开mysql监控");
        $("#Mysqlbox").hide("slow")     
        $("#OpenMysql").attr("data-status","yes");
    }
}
//关闭后台数据库监控
function closeMysql(status){
    if(ws){
        let Data = {};
        Data.type = "CLOSEMYSQL";
        Data.status = status;
        ws.send(json(Data))
    }
}
function hidenDebug(){
//    changeModel()
    $(".box").hide("slow");
    $(".openDebug").show("slow");
    $("#OpenMysql").attr("data-status","no")
    OpenMysql()
}
function openDebug(){
    //changeModel()
    $(".openDebug").hide("slow");
    $(".box").show("slow");
    $("#OpenMysql").attr("data-status","yes")
    OpenMysql()
}
function id(id){
    return document.getElementById(id);
}
//删除参数
function delParam(obj){
    $(obj).parent().remove()
    changeBoxHeight();
}
//添加参数
function addParam(){
    let keyValueType = "keyValueType" + Math.random()
    let str = `<p><input name="`+keyValueType+`" type="radio" value="normal" checked  />普通参数 <input name="`+keyValueType+`" type="radio" value="header"   /> Header参数<input name="`+keyValueType+`" type="radio" value="cookie"   />Cookie参数  &nbsp;&nbsp;&nbsp;&nbsp;Key：<input type='text' class='key' />`
    str += "Value：<input type='text' class='value' />"
    str += "<button onclick=delParam(this)>删除</button></p>"
    $("#params-form").append(str)
    changeBoxHeight();
}

//修改box高度
function changeBoxHeight(){
    if($("#debugModel option:selected").val() != "YALI-GET" && $("#debugModel option:selected").val() != "YALI-POST"){
        var h = 216 + 55 * ($("#params-form p").length - 1); 
        $(".box").animate({
            height: h + "px",
        },800)   
    }
}
//查看全部
function readAll(){
    $(".apiBody pre .jindu").animate({
        top:"0px",
    },1000)
    $(".readAll").remove(); //删除该元素
}

//编辑器制造对应行数
function createLingNumbers(){
    let regexp = new RegExp("\n", "g");
    res = $("#code").val().match(regexp)
    if(!res || res.length == null){
        return
    }
    let c = res.length
    //ChangeRows()
    if (c > 100){   
        $("#code").attr("row",c);   
    }
    let h = (c * 20) + 100 + "px"
    $(".codeMain").css("height",h);
    $("#code").css("height",(c * 20) + "px");
    //开始制造行数
    str = ""
    for(let i = 1; i <= c; i++){
        str += "<p>" + i + "</p>"
    }
    $(".codeLline").html(str) //清空行数
}
//初始化iframe的宽高
window.onload = function(){

    var iframe = id("iframe");
    PageWidth  = window.screen.width
    PageHeight = window.screen.height
    iframe.style.width = window.screen.width+"px";
    iframe.style.height = window.screen.height+"px";
    $("#iframeWidthSet").val(parseInt(window.screen.width));
    $("#iframeWidthSet").attr("max",parseInt(window.screen.width));
    $("#debugModel").find("option[value='NORMAL']").attr("selected", "selected");
    $(".codeBox").animate({
        display:"block",
        width: parseInt(PageWidth) / 2 + "px",
    },800);
    //初始化编程语言
    let ops = ""
    for(let i = 0; i < Langs.length; i++){
        ops += '<option value="' + Langs[i][1] + '">' + Langs[i][0] + '</option>'
    }
    $("#SetLang").html(ops) 
    ChangeCodeBoxWidth()
    //验证宽度
    if(PageWidth < 1920){
        layer.msg("您的分辨率过低，系统不建议使用，请使用1920*1080或更高的分辨率体验！")
    }

    //增加拖曳组件
   Drag()

    var host = window.location.host
    ws = new WebSocket("ws://" + host.replace(":8080","") + ":8081/ws");

    ws.onopen = function(e) {
        echo("连接成功！");
        var data = {}
        data.message = "来！宝贝儿，mysql监控走起！"
        data.type = "mysql"
        messageJson = json(data);
        ws.send(messageJson)   
    }
    ws.onclose = function(evt) {
        echo("连接关闭");
        ws = null;
    }
    ws.onmessage = function(e) {
        data = $.parseJSON(e.data);
        if (data.type == "mysql"){
            id("Mysqlbox").innerHTML = data.logs
        }else if(data.type == "ADDDIR"){
            if(data.path.length > 0 && data.status == "yes"){
                let Data = {};
                Data.type = "GetPathInfo";
                Data.data = data.path;
                ws.send(json(Data))
            }else{
                alert("创建失败！" + data.body)
            }
        }else if(data.type == "DELDIR"){
            if(data.status == "no"){
                alert("删除失败")
            }else{
                let Data = {};
                Data.type = "GetPathInfo";
                Data.data = data.path;
                ws.send(json(Data))
            }
        }else if(data.type == "api"){
            $(".apiBody pre").html(data.body)
            let header = "<hr/>"
            if(data.header){
                for(k in data.header){
                    header += "<p style='color:#000;padding:2px;font-size:16px;font-weight:normal;'>" + k + "：  " + data.header[k] + "</p>"
                }
            }
            $(".apiBody pre .HaoShi").html($(".apiBody pre .HaoShi").html() + header)
        }else if(data.type == "STRREPLACE"){
            $(".apiBody pre .jieguo").html(data.body + $(".apiBody pre .jieguo").html())
        }else if(data.type == "STRSEARCH" || data.type == "DIRSEARCH"){
            if(data.jindu == "yes" && data.status == "no"){
                $(".apiBody pre .jindu").html(data.path)
            }else if(data.status == "no" && data.jindu == "runing"){
                $(".apiBody pre .progress-span").html(data.progress)
                $(".apiBody pre  progress").val(data.progress)           
            }else if(data.status == "no" && data.jindu == "yes"){
                $(".apiBody pre .jindu").html(data.body)
            }else if(data.status == "yes" && !data.haoshi){
                $(".apiBody pre .jieguo").append(data.body)
            }else{
                $(".apiBody pre .jindu").html(data.body)
            }
        }else if(data.type == "GetFileInfo"){
            let model = $("#debugModel option:selected").val()
            let path = data.path
            //网页 api模式
            //if($.inArray(model,fileSystemModels) != -1){
                if(data.status == "no"){
                    alert(data.body)
                    $(".fileDir").html("")
                    $("#code").attr("readonly","readonly")
                    return
                }

                //准备打开列表
                //先判断目录是否已经打开
                if($.inArray(path,fileOpenLists) == -1){
                    fileOpenLists.push(path)
                }
                iniFileOpenLists(path)
                //给关闭按钮添加事件
                $(".fileLists >button .close").bind("click",function(event){
                    event.stopPropagation();//阻止冒泡
                    removeEdit(this)
                })
                $("#code").removeAttr("readonly")
                $("#codeBoxWidthSet").val(parseInt(PageWidth) / 2)
                $("#codeBoxWidthSet").attr("max",parseInt(PageWidth))
                $(".fileDir").html(data.path)
                codeMain = ace.edit("codeMain",{
                    wrap: true,
                    showInvisibles:false,
                    showPrintMargin: false,
                    enableBasicAutocompletion: true,
                    enableSnippets: true,
                    enableLiveAutocompletion: true,
                    useSoftTabs:false,
                    tabSize:4,
                    keyboardHandler:'sublime',
                    theme:"ace/theme/monokai"
            });
            codeMain.resize();
           // editor.setTheme("ace/theme/monokai");
            codeMain.setValue(data.body)
            Lang(codeMain,data.path)
            $("#codeMain").css({
                width: $(".codeBox").width + "px",
                height: PageHeight - 300 + "px"
            })
            //解决第一次打开文件闪移问题
            if(fileOpenLists.length <= 1 && openEditCounts == 0){
                //在渲染一次
                openEdit()
                openEditCounts++
            }
            return //为了渲染性能下面不执行
            //}
            if(data.status == "no"){
                $(".apiBody pre").html("<h1>" + data.body +"</h1>" )
                return 
            }
            let editorHtml = '<div id="editor"></div>'
            $(".apiBody pre").html(editorHtml).css({width:100 + "%",margin:0})
            //$(".nowPath").html(data.path)
            editor = ace.edit("editor",{
                readOnly:true
            });
            editor.setValue(data.body)
            editor.setTheme("ace/theme/monokai");
            Lang(editor,data.path)
            $("#editor").css({
                minHeight:PageHeight + "px"
            });
        }else if(data.type == "GetPathInfo"){
            if(data.status == "no"){
                $(".apiBody pre").html("<h1>" + data.body +"</h1>" )
                return 
            }
            $(".dirLists").html(data.body)
            if (data.path != "disk") {
                $(".nowPath").html(data.path)
            }else{
                $(".nowPath").html("")
            }
            bindDel()
        }else if(data.type == "IPTOCITY" || data.type == "TIMETODATE"){
            $(".apiBody pre").html("<h1>" + data.body +"</h1>" )
        }else if(data.type == "REGXP"){
            $("#regStr").val( data.body)
            updateModelsUrlValues();
        }else if(data.type == "PressureTest"){
            if (data.status == "err"){
                $("#DeBug").css("pointer-events","auto")
                ShowMsg(data.body)
            }else if (data.finish) {
                $(".apiBody pre .jindu").append(data.body)
                var progress = (parseFloat(data.finish) / parseFloat(data.total)  * 100).toFixed(2)
                $(".apiBody pre .JieGuo .progress-span").html(progress)
                $(".apiBody pre .JieGuo progress").val(progress)
                var n = parseInt($(".apiBody").innerHeight()) / 18 ;
                if(parseInt(data.finish) > n){
                    var top = (parseInt(data.finish) - n) * 18;
                    $(".apiBody pre .jindu").css("top", "-" + top + "px")
                    if (parseInt(data.finish) == parseInt(data.total)){
                        $(".apiBody pre .jindu").css("top", "-" + (top + 75) + "px")
                        $(".apiBody pre .jindu").append('<button onclick="readAll()" class="readAll">查看全部</button>')
                    }
                }
            }else{
                $(".apiBody pre .JieGuo").append(data.body)
                $("#DeBug").css("pointer-events","auto")
            }
        }
    }
    ws.onerror = function(evt) {
        echo("ERROR: " + evt.data);
    }
    changeModel()
};

function json(obj){
    return JSON.stringify(obj);
}
function echo($) {
    console.log($);
}

function ShowMsg(str) {
    $("#ShowMsg").html("<i>" + str + "</i>");
    $(".apiBody pre").html("<h1>" + str + "</h1>");
}